// 修复供应商表脚本
// 添加缺失的organization_id字段

const { exec } = require('child_process');

// MySQL连接配置
const mysqlConfig = {
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: '',  // 根据实际情况修改
  database: 'lingxi_system'
};

// 构建MySQL命令
function buildMysqlCommand(query) {
  return `mysql -h ${mysqlConfig.host} -P ${mysqlConfig.port} -u ${mysqlConfig.user} ${mysqlConfig.password ? `-p${mysqlConfig.password}` : ''} ${mysqlConfig.database} -e "${query}"`;
}

// 执行MySQL命令
function executeMysqlCommand(query) {
  return new Promise((resolve, reject) => {
    const command = buildMysqlCommand(query);
    console.log(`执行命令: ${command}`);
    
    exec(command, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行失败: ${error.message}`);
        reject(error);
        return;
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`);
        reject(new Error(stderr));
        return;
      }
      console.log(`执行成功: ${stdout}`);
      resolve(stdout);
    });
  });
}

async function fixSuppliersTable() {
  try {
    console.log('开始修复供应商表...');
    
    // 检查是否有organization_id字段
    console.log('检查suppliers表结构...');
    const describeResult = await executeMysqlCommand('DESCRIBE suppliers');
    console.log('当前表结构:');
    console.log(describeResult);
    
    // 检查是否包含organization_id字段
    if (describeResult.includes('organization_id')) {
      console.log('organization_id字段已存在，无需添加');
    } else {
      console.log('添加organization_id字段...');
      await executeMysqlCommand('ALTER TABLE suppliers ADD COLUMN organization_id INT NOT NULL DEFAULT 1;');
      console.log('organization_id字段添加成功');
    }
    
    console.log('供应商表修复完成');
  } catch (error) {
    console.error('修复失败:', error.message);
    
    // 尝试使用root密码
    if (error.message.includes('Access denied') && !mysqlConfig.password) {
      console.log('尝试使用root密码...');
      mysqlConfig.password = 'root';
      try {
        await fixSuppliersTable();
      } catch (error2) {
        console.error('使用root密码也失败:', error2.message);
      }
    }
  }
}

// 执行修复
fixSuppliersTable();